"""
    Controller for curstomer table.
"""

from turbogears import identity, expose
from mnemoply import model
from mnemoply.mass_actions import MassAction
from mnemoply.controllers.lookup_new import LookupController, TableCol, TableLookupDataSource
from mnemoply.controllers.crud import  ItemActionsTab
from mnemoply.controllers.crud_new import RestrictController, CRUDController
from mnemoply.utils import PhoneFormat

class AgreementItemTab(ItemActionsTab):
    title = _("Agreements")
    name = "agreements_tab"
    ma_class_name = 'StudentAgreement'

    def getRecords(self, obj):
        agrs = list(model.StudentAgreement.selectBy(customer=obj))
        agrs.sort(key=lambda x: x.title)
        return agrs

    def getRecordTitle(self, obj):
        return obj.title

class MATransformToPartner(MassAction):
    target_class = model.Customer
    name = "transform_to_partner"
    title = _("Transform to partner")

    def call(self, objs):
        p_type = model.PartnerType.get(2) #FIXME
        office = identity.current.user.office
        for o in objs:
            model.Partner(
                partnerType=p_type,
                surname=o.surname,
                forename=o.forename,
                patronymic=o.patronymic,
                phone=o.phone,
                email=o.email,
                password=model.Partner.createNewPassword(office),
                office=office
                )

class CustomerController(CRUDController):
    model_object = model.Customer
    lookup_columns = [
        TableCol(name='surname', caption=_('Surname')),
        TableCol(name='forename', caption=_('Forename')),
        TableCol(name='patronymic', caption=_('Patronymic')),
        TableCol(name='phone', caption=_('Phone')),
        TableCol(name='phone_main', caption=_('Main phone')),
        TableCol(name='phones_more', caption=_('More phones')),
        TableCol(name='email', caption=_('e-mail'), hidden=True, size=9),
        TableCol(name='office', caption=_('Offices'), hidden=True),
        TableCol(name='cache_groups', caption=_('Groups'), hidden=True),
        TableCol(name='count_agreement', caption=_('Amount of agreement'), hidden=True),
        TableCol(name='count_student', caption=_('Amount of students'), hidden=True),
   ]

    edit_fields = [
        'surname',
        'forename',
        'patronymic',
        'phone',
        'phone_main',
        'phones_more',
        'email',
        ]

    view_fields = edit_fields

    item_tabs = [AgreementItemTab()]

    #def __init__(self, data_source=TableLookupDataSource('customer_lookup')):
    #    LookupController.__init__(self,
    #        data_source=data_source,
    #        columns=self.lookup_columns,
    #        mass_actions_class=self.model_object,
    #        title=self.model_object.model_title,
    #        default_order_by='surname',
    #    )
    #    CRUDController.__init__(self, model_object=self.model_object)

    @expose()
    def check_phone(self,obj,**kw):
        str_phone = PhoneFormat.to_python(kw['phone_main'])
        if (str_phone == PhoneFormat.bad_str()):
            res = "%s"%(PhoneFormat.bad_str(True))
            return dict(result_check_phone = res)
        dict_phone = PhoneFormat.from_python(str_phone)
        num = '%'+dict_phone['num']+'%'
        cst = model.Customer.select("replace(phones_more,'-','')LIKE '%s'"%num)
        cst1 = model.Customer.selectBy(phone_main=str_phone)
        count_all = cst.count()
        count_main = cst1.count()
        res = """%s
%s:  %s
%s:  %s
        """%(str_phone,_('More phones'), count_all, _('Main phone'),count_main)
        return dict(result_check_phone=res)
    check_phone.expose_object = True

exposed = CustomerController()
